package com.wavejo.reactor.handler;

import com.wavejo.reactor.pojo.User;
import com.wavejo.reactor.service.UserService;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import static org.springframework.web.reactive.function.BodyInserters.fromObject;

/**
 * @Author WaveHi
 * @Date 26/10/2021 下午 6:10
 * @Version 1.0
 * @Contact HJBWaveHi@163.com
 * @Description
 */
public class UserHandler {
    private UserService userService;
    public UserHandler(UserService userService) {
        this.userService = userService;
    }
    public Mono<ServerResponse> getData(ServerRequest request) {
        //获取传递过来的参数
        Long id = Long.valueOf(request.pathVariable("id"));

        Mono<ServerResponse> notFound = ServerResponse.notFound().build();

        //调用业务层获取相应的数据
        Mono<User> user = userService.getUser(id);
        //将数据转换为流进行返回
        return user.flatMap(u -> ServerResponse.ok().contentType(MediaType.APPLICATION_JSON)
                .body(fromObject(u))).switchIfEmpty(notFound);
    }
    public Mono<ServerResponse> getAllUser(ServerRequest request) {
        Flux<User> allUser = userService.getAllUser();
        return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).body(allUser, User.class);
    }
    public Mono<ServerResponse> add(ServerRequest request) {
        Mono<User> userMono = request.bodyToMono(User.class);
        return ServerResponse.ok().build(userService.addUser(userMono));
    }
}
